// 处理登录表单提交
const loginForm = document.getElementById('loginForm');
if (loginForm) {
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        try {
            const response = await fetch('/api/login/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ username, password }),
            });

            if (response.ok) {
                const data = await response.json();
                localStorage.setItem('token', data.token);
                window.location.href = '../index.html';
            } else {
                alert('登录失败，请检查用户名和密码');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('登录失败，请稍后重试');
        }
    });
}

// 处理注册表单提交
const registerForm = document.getElementById('registerForm');
if (registerForm) {
    registerForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        const phone = document.getElementById('phone').value;
        const address = document.getElementById('address').value;
        const role = document.getElementById('role').value;

        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            return;
        }

        try {
            const response = await fetch('/api/register/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username,
                    password,
                    phone,
                    address,
                    role
                }),
            });

            if (response.ok) {
                alert('注册成功！');
                window.location.href = 'login.html';
            } else {
                alert('注册失败，请稍后重试');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('注册失败，请稍后重试');
        }
    });
}
